package com.comdo.newup_loan.module.myinfo;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.comdo.newup_loan.BankWebViewActivity;
import com.comdo.newup_loan.R;
import com.comdo.newup_loan.base.BaseActivity;
import com.comdo.newup_loan.comom.Config;
import com.comdo.newup_loan.model.KeyValueBean;
import com.comdo.newup_loan.model.NativeBean;
import com.comdo.newup_loan.model.UpLoadCard;
import com.comdo.newup_loan.model.UserBaseInfo;
import com.comdo.newup_loan.util.StringUtils;
import com.comdo.newup_loan.util.TitleMenuUtil;
import com.comdo.newup_loan.widget.mySpinner.ComomData;
import com.comdo.newup_loan.widget.mySpinner.MySpinner;
import com.comdo.newup_loan.widget.mySpinner.onResultListener;
import com.liji.imagezoom.util.ImageZoom;
import com.liji.takephoto.TakePhoto;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by liyuan on 2017/11/3.
 */

public class MyInfoActivity extends BaseActivity<MyInfoPresenter> implements MyInfoContract.View, View.OnClickListener {
    @BindView(R.id.tv_name)
    TextView mNameText;
    @BindView(R.id.tv_card_no)
    TextView mCardNoText;
    @BindView(R.id.tv_phone)
    TextView mPhoneText;
    @BindView(R.id.tv_bank_card)
    TextView mBankText;
    @BindView(R.id.tv_income)
    TextView mIncomeText;
    @BindView(R.id.tv_Liabilities)
    TextView mLiabilitiesText;
    @BindView(R.id.tv_industry)
    TextView mIndustryText;
    @BindView(R.id.tv_sex)
    TextView mSexText;
    @BindView(R.id.tv_native)
    TextView mNativeText;
    @BindView(R.id.ed_email)
    EditText mEmailEdText;
    @BindView(R.id.img_upload)
    ImageView mUpLoadImg;
    @BindView(R.id.img_upload_back)
    ImageView mUpLoadBackImg;
    @BindView(R.id.rl_font)
    RelativeLayout mFontLayout;
    @BindView(R.id.rl_back)
    RelativeLayout mBackLayout;
    @BindView(R.id.btn_submit)
    Button mSubmitbtn;
    @BindView(R.id.rl_bank_card)
    RelativeLayout mBankLayout;
    private List<NativeBean> citys = new ArrayList<NativeBean>();
    private List<KeyValueBean> incomeList = new ArrayList<KeyValueBean>();
    private List<KeyValueBean> liabilitiesList = new ArrayList<KeyValueBean>();
    private static List<KeyValueBean> sex = new ArrayList<KeyValueBean>();
    private MySpinner sp_citys, sp_sex,sp_income,sp_liabilities;
    private String province;
    private String city;
    private String cityId;
    private String sexid;
    private int incomeId=-1;
    private int industrycategoryId=-1;
    private int liabilitiesId=-1;
    private UserBaseInfo userBaseInfo;
    private Boolean isFontUpLoad = true;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_myinfo;
    }

    @Override
    protected void init() {
        super.init();
        userBaseInfo = new UserBaseInfo();
        mPresenter.getInfo(Config.loginInfo.getUserId());
        mPresenter.getNativePlace();
        getSex();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        new TitleMenuUtil(MyInfoActivity.this, "个人信息", false);
        mSubmitbtn.setOnClickListener(this);
        mUpLoadImg.setOnClickListener(this);
        mUpLoadBackImg.setOnClickListener(this);
        mFontLayout.setOnClickListener(this);
        mBackLayout.setOnClickListener(this);
        mNativeText.setOnClickListener(this);
        mBankLayout.setOnClickListener(this);
        mSexText.setOnClickListener(this);
        mIncomeText.setOnClickListener(this);
        mLiabilitiesText.setOnClickListener(this);
        mIndustryText.setOnClickListener(this);
    }

    @Override
    public void Fail(String failMessage) {
        showToast(failMessage);
    }

    @Override
    public void getBaseInfo(UserBaseInfo userBaseInfo) {
        this.userBaseInfo = userBaseInfo;

        mNameText.setText(userBaseInfo.getName());
        mCardNoText.setText(userBaseInfo.getCardNum());
        mPhoneText.setText(userBaseInfo.getPhone());
        mBankText.setText(userBaseInfo.getBankAccount());
        if (!StringUtils.isNull(userBaseInfo.getSex()))
            mSexText.setText(userBaseInfo.getSex().equals("0") ? "男" : userBaseInfo.getSex().equals("1")?"女":"请选择");
        sexid = userBaseInfo.getSex();
        cityId = userBaseInfo.getCityId();
        mNativeText.setText(userBaseInfo.getCityName());
        mEmailEdText.setText(userBaseInfo.getEmail());
        if (!StringUtils.isNull(userBaseInfo.getIdentityCardFront())) {
            Glide.with(MyInfoActivity.this).load(Config.PIC_FORE + userBaseInfo.getIdentityCardFrontUrl()).into(mUpLoadImg);
        }
        if (!StringUtils.isNull(userBaseInfo.getIdentityCardReverse())) {
            Glide.with(MyInfoActivity.this).load(Config.PIC_FORE + userBaseInfo.getIdentityCardReverseUrl()).into(mUpLoadBackImg);
        }
        incomeId=userBaseInfo.getIncomeId();
        liabilitiesId=userBaseInfo.getLiabilitiesId();
        industrycategoryId=userBaseInfo.getIndustrycategoryId();
        incomeList=userBaseInfo.getIncomeList();
        liabilitiesList =userBaseInfo.getLiabilitiesList();
        mIncomeText.setText(userBaseInfo.getIncomeValue().equals("")?"请选择":userBaseInfo.getIncomeValue());
        mLiabilitiesText.setText(userBaseInfo.getLiabilitiesValue().equals("")?"请选择":userBaseInfo.getLiabilitiesValue());
        mIndustryText.setText(userBaseInfo.getIndustrycategoryValue().equals("")?"请选择":userBaseInfo.getIndustrycategoryValue());
    }

    @Override
    public void changeCard(String result) {
        mPresenter.getXwWeb(MyInfoActivity.this);
    }

    @Override
    public void getXwWeb(String url) {
        toXwWeb(url);
    }

    private void toXwWeb(String url) {
        Intent intent = new Intent(MyInfoActivity.this, BankWebViewActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @Override
    public MyInfoPresenter getmPresenter() {
        return new MyInfoPresenter();
    }

    @Override
    public void presenterSetView() {
        if (mPresenter != null)
            mPresenter.setView(this);
    }

    @Override
    public void saveInfo(String result) {
        showToast(result);
        MyInfoActivity.this.finish();
    }

    @Override
    public void getNativePlace(List<NativeBean> datas) {
        citys.clear();
        citys.addAll(datas);
    }

    @Override
    public void upLoad(UpLoadCard result) {
        if (userBaseInfo != null) {
            if (isFontUpLoad) {
                userBaseInfo.setIdentityCardFront(result.getId() + "");
                userBaseInfo.setIdentityCardFrontUrl(result.getUrl());
                Glide.with(MyInfoActivity.this).load(Config.PIC_FORE + result.getUrl()).into(mUpLoadImg);
            } else {
                userBaseInfo.setIdentityCardReverse(result.getId() + "");
                userBaseInfo.setIdentityCardReverseUrl(result.getUrl());
                Glide.with(MyInfoActivity.this).load(Config.PIC_FORE + result.getUrl()).into(mUpLoadBackImg);
            }
        }

    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.tv_native:

                if (citys == null || citys.size() == 0)
                    return;
                if (sp_citys == null) {
                    sp_citys = new MySpinner(MyInfoActivity.this, citys, 2);
                    sp_citys.setOnResultListener(new onResultListener() {

                        @Override
                        public void onResult(Object obj) {
                            if (obj != null) {
                                province = ((ComomData) sp_citys.getWheelViewOne()
                                        .getSeletedItem()).getMyName();
                                city = ((ComomData) obj).getMyName();

                                ((TextView) v).setText(province + city);
                                cityId = ((ComomData) obj).getMyId() + "";

                            }
                        }
                    });
                } else {
                    sp_citys.show();
                }
                break;
            case R.id.tv_income:

                if (incomeList == null || incomeList.size() == 0)
                    return;
                if (sp_income == null) {
                    sp_income = new MySpinner(MyInfoActivity.this, incomeList, 1);
                    sp_income.setOnResultListener(new onResultListener() {

                        @Override
                        public void onResult(Object obj) {
                            if (obj != null) {
                               String str = ((ComomData) sp_income.getWheelViewOne()
                                        .getSeletedItem()).getMyName();
                                ((TextView) v).setText(str);
                                incomeId = ((ComomData) obj).getMyId();

                            }
                        }
                    });
                } else {
                    sp_income.show();
                }
                break;
            case R.id.tv_Liabilities:

                if (liabilitiesList == null || liabilitiesList.size() == 0)
                    return;
                if (sp_liabilities == null) {
                    sp_liabilities = new MySpinner(MyInfoActivity.this, liabilitiesList, 1);
                    sp_liabilities.setOnResultListener(new onResultListener() {

                        @Override
                        public void onResult(Object obj) {
                            if (obj != null) {
                                String str = ((ComomData) sp_liabilities.getWheelViewOne()
                                        .getSeletedItem()).getMyName();
                                ((TextView) v).setText(str);
                                liabilitiesId = ((ComomData) obj).getMyId();
                            }
                        }
                    });
                } else {
                    sp_liabilities.show();
                }
                break;
            case R.id.tv_industry:
                Intent intent=new Intent(MyInfoActivity.this,IndustryActivity.class);
                intent.putExtra("type",0);
                startActivity(intent);
                break;
            case R.id.tv_sex:
                if (sp_sex == null) {
                    sp_sex = new MySpinner(MyInfoActivity.this, sex, 1);
                    sp_sex.setOnResultListener(new onResultListener() {
                        @Override
                        public void onResult(Object obj) {
                            if (obj != null) {
                                ((TextView) v).setText(((ComomData) obj)
                                        .getMyName());
                                sexid = ((ComomData) obj).getMyId() + "";
                            }
                        }
                    });
                } else {
                    sp_sex.show();
                }
                break;
            case R.id.btn_submit:
                UserBaseInfo user = new UserBaseInfo();
                user.setSex(sexid + "");
                user.setCityId(cityId + "");
                user.setIncomeId(incomeId);
                user.setLiabilitiesId(liabilitiesId);
                user.setIndustrycategoryId(industrycategoryId);
                user.setEmail(mEmailEdText.getText().toString());
                if (userBaseInfo != null) {
                    user.setIdentityCardFront(userBaseInfo.getIdentityCardFront());
                    user.setIdentityCardReverse(userBaseInfo.getIdentityCardReverse());
                }
                Verify();
                mPresenter.saveInfo(Config.loginInfo.getUserId(), user);
                break;
            case R.id.rl_font:

                //TakePhotoDialog(0);
                break;
            case R.id.rl_back:
                //  TakePhotoDialog(1);

                break;
            case R.id.img_upload:

                if (userBaseInfo != null && !StringUtils.isNull(userBaseInfo.getIdentityCardFrontUrl())) {
                    showSelectDialog(0);
                } else {
                    TakePhotoDialog(0);
                }

                break;
            case R.id.img_upload_back:
                if (userBaseInfo != null && !StringUtils.isNull(userBaseInfo.getIdentityCardReverseUrl())) {
                    showSelectDialog(1);
                } else {
                    TakePhotoDialog(1);
                }

                break;
            case R.id.rl_bank_card:
                //mPresenter.changeCard(Config.loginInfo.getUserId());
                break;
        }
    }
    private boolean Verify(){
        if(incomeId==-1){
            showToast("月收入为必填！");
            return false;
        }
        if(industrycategoryId==-1){
            showToast("所属行业为必填！");
            return false;
        }
        if(liabilitiesId==-1){
            showToast("负债为必填！");
            return false;
        }
        if(("-1").equals(userBaseInfo.getIdentityCardFront())){
            showToast("身份证正面为必填！");
            return false;
        }
        if(("-1").equals(userBaseInfo.getIdentityCardReverse())){
            showToast("身份证反面为必填！");
            return false;
        }
        return true;
    }
    private void getSex() {
        sex.clear();
        KeyValueBean key = new KeyValueBean();
        key.setId(0);
        key.setName("男");
        sex.add(key);
        key = new KeyValueBean();
        key.setId(1);
        key.setName("女");
        sex.add(key);
    }

    private void showSelectDialog(final int type) {
        final String[] items = new String[]{"更改图片", "查看大图"};
        // 创建对话框构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置参数
        builder.setTitle("请选择")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            TakePhotoDialog(type);
                        } else {
                            String url = type == 0 ? Config.PIC_FORE + userBaseInfo.getIdentityCardFrontUrl() : Config.PIC_FORE + userBaseInfo.getIdentityCardReverseUrl();
                            ImageZoom.show(MyInfoActivity.this, url, ImageZoom.LOCAL);
                        }
                    }
                });
        builder.create().show();
    }

    private void TakePhotoDialog(final int type) {
        TakePhoto takePhoto = new TakePhoto(MyInfoActivity.this);
        takePhoto.setOnPictureSelected(new TakePhoto.onPictureSelected() {
            @Override
            public void select(String path, String compresspath) {
                if (type == 0) {
                    isFontUpLoad = true;
                    mPresenter.upLoad(Config.loginInfo.getUserId(), compresspath, 0);
                } else {
                    isFontUpLoad = false;
                    mPresenter.upLoad(Config.loginInfo.getUserId(), compresspath, 1);
                }

            }
        });
        takePhoto.show();
    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("我的信息");
        MobclickAgent.onResume(this);

       if(Config.industryBean!=null){
           mIndustryText.setText(Config.industryBean.getIndustryName());
           industrycategoryId=Config.industryBean.getId();
       }
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("我的信息");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Config.industryBean=null;
    }
}
